import { reqLogin,reqRegister,reqGetUserInfoByCookie,reqLogout,reqUpdateUserInfo,reqUploadAvatar } from "@/api"

const actions = {
    async register({commit},registerInfo){
        let result = await reqRegister(registerInfo)

        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(result.msg)
        }
    },

    async login({commit},loginInfo){
        let result = await reqLogin(loginInfo)

        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(result.msg)
        }
    },

    async getUserInfo({commit}){
        let result = await reqGetUserInfoByCookie()

        if(result.code == 200){
            commit('GETUSERINFO',{userInfo:result.data,canIGetUserInfo:true})
            return true
        }else{
            return Promise.reject(false)
        }
    },

    async logout({commit}){
        let result = await reqLogout()

        if(result.code == 200){
            commit('LOGOUT',{userInfo:{},canIGetUserInfo:false})
            return result.msg
        }else{
            return Promise.reject('服务器异常')
        }
    },

    async updateUserInfo({commit},updatedInfo){
        let result = await reqUpdateUserInfo(updatedInfo)

        if(result.code == 200){
            return result.msg
        }else{
            return Promise.reject(result.msg)
        }
    },

    async uploadAvatar({commit,dispatch},formData){
        let result = await reqUploadAvatar(formData)
        if(result.code == 200){
            await dispatch("getUserInfo")
            return 'ok'
        }else{
            Promise.reject('上传失败')
        }
    }

}

const mutations = {
    GETUSERINFO(state,value){
        let {userInfo,canIGetUserInfo} = value
        state.userInfo = userInfo 
        state.canIGetUserInfo = canIGetUserInfo
    },

    LOGOUT(state,value){
        let {userInfo,canIGetUserInfo} = value
        state.userInfo = userInfo 
        state.canIGetUserInfo = canIGetUserInfo
    }
}

const state = {
    userInfo:{},
    canIGetUserInfo:false
}

const getters = {

}

export default {
    actions,
    mutations,
    state,
    getters
}